package org.zhq.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.zhq.Const;
import org.zhq.ServerResult;
import org.zhq.enums.OrderStatusEnum;
import org.zhq.enums.PayMethod;
import org.zhq.pojo.bo.ShopCartBO;
import org.zhq.pojo.bo.SubmitOrderBO;
import org.zhq.pojo.vo.MerchantOrdersVO;
import org.zhq.pojo.vo.OrderVO;
import org.zhq.service.OrderService;
import org.zhq.utils.CookieUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Api(value = "订单接口", tags = {"订单相关接口"})
@RestController
@RequestMapping("orders")
@Slf4j
public class OrdersController {

    private final OrderService orderService;
    private final RestTemplate restTemplate;
    private final StringRedisTemplate redisTemplate;

    @Autowired
    public OrdersController(OrderService orderService, RestTemplate restTemplate, StringRedisTemplate redisTemplate) {
        this.orderService = orderService;
        this.restTemplate = restTemplate;
        this.redisTemplate = redisTemplate;
    }

    @ApiOperation(value = "用户下单", notes = "用户下单", httpMethod = "POST")
    @PostMapping("/create")
    public ServerResult create(@RequestBody SubmitOrderBO submitOrderBO,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        if (!submitOrderBO.getPayMethod().equals(PayMethod.WEIXIN.type)
                && !submitOrderBO.getPayMethod().equals(PayMethod.ALIPAY.type)) {
            return ServerResult.errorMsg("支付方式不支持!");
        }
        String shopCartStr = redisTemplate.opsForValue().get(Const.Redis.SHOP_CART + ":" + submitOrderBO.getUserId());
        if (StrUtil.isBlank(shopCartStr)) {
            return ServerResult.errorMsg("购买数据不正确");
        }
        //0.创建订单
        List<ShopCartBO> shopCartBOList = JSONUtil.toList(JSONUtil.parseArray(shopCartStr), ShopCartBO.class);
        OrderVO orderVO = orderService.createOrder(shopCartBOList, submitOrderBO);
        String orderId = orderVO.getOrderId();
        //1.向支付中心发送当前订单，用于保存支付中心的订单数据
        ServerResult result = sendOrderToPaymentCenter(orderVO);
        if (!result.isOK()) {
            return ServerResult.errorMsg("支付中心订单创建失败,联系管理员");
        }
        //2.移除购物车中已结算的商品
        shopCartBOList.removeAll(orderVO.getToBeRemoveShopCartList());
        redisTemplate.opsForValue().set(Const.Redis.SHOP_CART + ":" + submitOrderBO.getUserId(), JSONUtil.toJsonStr(shopCartBOList));
        CookieUtils.setCookie(request, response, Const.Redis.SHOP_CART, JSONUtil.toJsonStr(shopCartBOList));
        return ServerResult.ok(orderId);
    }

    //向支付中心发送当前订单，用于保存支付中心的订单数据
    private ServerResult sendOrderToPaymentCenter(OrderVO orderVO) {
        MerchantOrdersVO merchantOrdersVO = orderVO.getMerchantOrdersVO();
        merchantOrdersVO.setReturnUrl(Const.PAY_RETURN_URL);
        merchantOrdersVO.setAmount(1);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("imoocUserId", "imooc");
        headers.add("password", "imooc");
        HttpEntity<MerchantOrdersVO> entity = new HttpEntity<>(merchantOrdersVO, headers);
        log.info("请求url:{},参数:{}", Const.PAYMENT_URL, entity.toString());
        ResponseEntity<ServerResult> responseEntity = restTemplate.postForEntity(Const.PAYMENT_URL, entity, ServerResult.class);
        return responseEntity.getBody();
    }


    @ApiOperation(value = "支付回调(支付中心)", notes = "支付回调(支付中心)", httpMethod = "POST")
    @PostMapping("/notifyMerchantOrderPaid")
    public ServerResult notifyMerchantOrderPaid(String merchantOrderId) {
        orderService.updateOrderStatus(merchantOrderId, OrderStatusEnum.WAIT_DELIVER.type);
        return ServerResult.ok();
    }


}
